package com.yejiarong.common.validate;

import com.yejiarong.common.validate.annotation.ValueOption;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;

/**
 * @author YeJR
 */
public class ValueOptionValidate implements ConstraintValidator<ValueOption, Object> {

    private final HashSet<String> values = new HashSet<>();

    private boolean multiple;

    @Override
    public void initialize(ValueOption constraintAnnotation) {
        values.addAll(Arrays.asList(constraintAnnotation.values()));
        this.multiple = constraintAnnotation.multiple();
    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (Objects.nonNull(value) && !String.valueOf(value).trim().isEmpty()) {
            if (!multiple) {
                return values.contains(String.valueOf(value));
            } else {
                List<String> valList = Arrays.asList(String.valueOf(value).split(","));
                return values.containsAll(valList);
            }
        }
        return true;
    }
}
